<template>
	<view class="csgo-case-battle">
		<navgats :images="img"></navgats>
		<!-- 顶部宝箱区域 -->
		<view class="cases-container">
			<scroll-view class="cases-scroll" scroll-x>
				<view class="cases-list">
					<view class="case-item" v-for="(arenaBox, index) in game_arena_box" :key="arenaBox.uniqueId"
						:class="{ 'active': currentOpeningIndex === index, 'opened': arenaBox.box.opened, 'selected': selectedBoxIndex === index }"
						v-if="arenaBox.box && arenaBox.box.intact_cover" @click="showBoxRewards(arenaBox.box, index)">
						<image class="case-cover" :src="arenaBox.box.intact_cover" mode="widthFix" :lazy-load="true"
							:alt="arenaBox.box.name"></image>
						<view class="case-name">{{ arenaBox.box.name }}</view>
						<view class="case-price">
							<view class="icon">

							</view>
							<view class="text">
								{{ arenaBox.box.game_bean }}
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- 房间信息 -->
		<view class="room-info" v-if="!isBattleStarted">
			<view class="room-status">
				<text>房间状态:</text>
				<text class="status-text">{{ players.length }}/{{ maxPlayers }} 玩家已加入</text>
			</view>
		</view>
		<!-- 玩家信息预览区域 - 战斗未开始时显示 -->
		<view class="players-preview" v-if="!isBattleStarted">
			<view class="players-grid" :class="'grid-' + maxPlayers">
				<!-- 已加入的玩家 -->
				<view class="player-slot" v-for="i in maxPlayers" :key="i"
					:class="{ 'filled': players[i - 1], 'empty': !players[i - 1] }">
					<template v-if="players[i - 1]">
						<image class="avatar" :src="players[i - 1].user.avatar" mode="widthFix"
							:alt="players[i - 1].user.name"></image>
						<view class="player-name">{{ players[i - 1].user.name }}</view>
						<view class="status joined">已加入</view>
					</template>

					<template v-else>
						<view class="avatar-placeholder">
							<view class="add-icon">+</view>
						</view>
						<view class="player-name">等待玩家</view>
						<view class="status waiting">待加入</view>
					</template>
				</view>
			</view>
		</view>


		<!-- 加入房间区域 - 只有未满且当前用户未加入时显示 -->
		<view class="join-room" v-if="!isBattleStarted && players.length < maxPlayers && !isCurrentUserJoined">
			<button @click="joinRoom" class="join-btn">
				{{ players.length > 0 ? '加入房间' : '创建并加入房间' }}
			</button>
		</view>

		<!-- 等待其他玩家提示 -->
		<view class="waiting-players"
			v-if="!isBattleStarted && players.length > 0 && players.length < maxPlayers && isCurrentUserJoined">
			<view class="waiting-text">等待其他玩家加入... ({{ players.length }}/{{ maxPlayers }})</view>
		</view>

		<!-- 房间满人等待开始提示 -->
		<view class="room-full-waiting" v-if="!isBattleStarted && players.length >= maxPlayers && isCurrentUserJoined">
			<view class="waiting-content">
				<view class="waiting-icon">🎮</view>
				<view class="waiting-title">房间已满</view>
				<view class="waiting-subtitle">对战即将开始，请稍候...</view>
			</view>
		</view>

		<!-- 准备阶段倒计时 -->
		<view class="preparation-phase" v-if="isPreparingBattle">
			<view class="preparation-content">
				<view class="preparation-title">对战即将开始</view>
				<view class="countdown-display">{{ prepareCountdown }}</view>
				<view class="preparation-subtitle">请准备...</view>
			</view>
		</view>

		<!-- 对战区域 -->
		<view class="battle-area" v-if="isBattleStarted">
			<!-- 玩家信息 - 包含总价值和获胜样式 -->
			<view class="players-battle-info" :class="'grid-' + maxPlayers">
				<view class="battle-player" v-for="i in maxPlayers" :key="i"
					:class="{ 'winner': isBattleEnded && getPlayerTotal(i - 1) > getMaxOtherPlayerTotal(i - 1) }"
					v-if="players[i - 1]">
					<image class="avatar" :src="players[i - 1].user.avatar" mode="widthFix"
						:alt="players[i - 1].user.name">
					</image>
					<view class="player-name"
						style="width: 90%; overflow: hidden; white-space: nowrap;text-overflow: ellipsis;">
						{{ players[i - 1].user.name }}
					</view>
					<view class="total-value">
						<view class="icon"></view>{{ getPlayerTotal(i - 1) }}
					</view>
				</view>
			</view>

			<!-- 对战状态提示 -->
			<view class="battle-status" v-if="!isBattleEnded">
				<text>正在对战中</text>
				<text class="current-box">当前开箱: {{ currentBoxName }}</text>
			</view>
			<view class="battle-status ended" v-if="isBattleEnded">
				<text v-if="isDraw()">平局</text>
				<text v-else>对战结束</text>
			</view>

			<!-- 调整：将开箱动画区域放在玩家信息下方 -->
			<view class="animation-container" v-if="!isBattleEnded">
				<view class="line">

				</view>
				<!-- 开箱动画区域 -->
				<view class="opening-area" v-if="isAnimating">
					<view class="player-opening" v-for="i in maxPlayers" :key="i" v-if="players[i - 1]">
						<open-several-box :ref="`player${i}Box`" :list="boxSkinsList" :result="getPlayerResult(i - 1)"
							:stopOffsetPercent="-10" :rowLength="1" :duration="5000" @finsh="onPlayerFinish(i - 1)">
							<template v-slot="{ item }">
								<view class="skin-item"
									:style="{ 
										backgroundImage: 'url(' + item.lv_bg_image + ')', 
										backgroundSize: 'cover', 
										padding: '20rpx' 
									}"
									v-if="item && item.cover">
									<image :src="item.cover" :alt="item.name || '饰品图片'"
										style="width:100rpx;height: 100rpx;"></image>
								</view>
							</template>
						</open-several-box>
					</view>
				</view>

				<!-- 显示当前开出的饰品 -->
				<view class="current-skin-display" v-if="!isAnimating && !isBattleEnded && currentResults.length">
					<view class="current-skin" v-for="i in maxPlayers" :key="i"
						v-if="players[i - 1] && currentResults[i - 1]">
						<image class="skin-image" :src="currentResults[i - 1].skins.cover"
							:alt="currentResults[i - 1].skins.name || '饰品图片'"></image>
						<view style="font-size: 24rpx;">
							{{ currentResults[i - 1].skins.name }}
						</view>
						<view class="skin-value">{{ currentResults[i - 1].skins.bean }} 豆</view>
					</view>
				</view>
			</view>
			<view class="victory" v-else-if="!isDraw()">
				<view class="item" v-for="(item,index) in maxPlayers" :key="index">
					<view class="item_box" v-if="isPlayerWinner(index)"></view>
					<text v-else-if="!isDraw() && isBattleEnded"></text>
				</view>
			</view>
		</view>

		<!-- 已开饰品列表 -->
		<view class="opened-skins" v-if="isBattleStarted">
			<view class="players-skins-container" :class="'grid-' + maxPlayers">
				<view class="player-skins" v-for="i in maxPlayers" :key="i" v-if="players[i - 1]">
					<view class="title">{{ players[i - 1].user.name }}已开饰品</view>
					<view class="skins-list">
						<view class="skin-item" v-for="(skin, index) in getPlayerSkins(i - 1)" :key="skin.id || index"
							:style="{ backgroundImage: 'url(' + skin.skins.lv_bg_image + ')' }">
							<template v-if="skin && skin.skins && skin.skins.cover">
								<image :src="skin.skins.cover" :alt="skin.skins.name || '饰品图片'" mode="widthFix"></image>
								<view class="skin-dura">{{ skin.skins.dura_alias }}</view>
								<view class="skin-details">
									<view class="skin-name">{{ skin.skins.name }}</view>

									<view class="skin-price">
										<view class="icon">

										</view>
										{{ skin.skins.bean }}
									</view>
								</view>
							</template>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 箱子奖励详情弹窗 -->
		<view class="reward-detail-modal" v-if="showRewardDetail">
			<view class="modal-overlay" @click="closeRewardDetail"></view>
			<view class="modal-content">
				<view class="modal-header">
					<text class="modal-title">{{ currentBoxDetail.name }} 包含的饰品</text>
					<button class="close-btn" @click="closeRewardDetail">×</button>
				</view>
				<view class="reward-list">
					<view class="reward-item" v-for="(item, index) in currentBoxDetail.contains" :key="index">
						<image :src="item.skins.cover" :alt="item.skins.name" mode="widthFix"></image>
						<view class="reward-info">
							<view class="reward-name">{{ item.skins.name }}</view>
							<view class="reward-dura">{{ item.skins.dura_alias }}</view>
							<view class="reward-value">{{ item.skins.bean }} 豆</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 错误提示 -->
		<view class="error-toast" v-if="errorMessage">
			<view class="toast-content">
				{{ errorMessage }}
				<button class="close-btn" @click="errorMessage = ''">确定</button>
			</view>
		</view>

		<!-- 加载中提示 -->
		<view class="loading" v-if="isLoading">
			<view class="loading-content">
				<view class="spinner"></view>
				<view class="loading-text">加载中...</view>
			</view>
		</view>

		<!-- 数据加载中提示，在战斗即将开始时显示 -->
		<view class="preparing-battle" v-if="isPreparingBattle">
			<view class="preparing-content">
				<view class="spinner"></view>
				<view class="preparing-text">准备战斗中... {{ prepareCountdown }}秒</view>
			</view>
		</view>

		<!-- 对战结果刷新提示 -->
		<view class="refreshing-battle" v-if="isRefreshingBattle">
			<view class="refreshing-content">
				<view class="spinner"></view>
				<view class="refreshing-text">获取最新对战结果中...</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getPKarenaDetail,
		getPKarenaJoin
	} from "../../../api/pk/pk.js"
	import globalWebSocket from '../../../utils/globalWebSocket.js';
	import navgats from "../../../Component/navgatsmy/navgatsmy.vue"
	import {
		playSound
	} from "../../../utils/soundSettings.js";
	export default {
		data() {
			return {
				// 基础数据
				img: "https://img.jingkakeji.com/img/static/pks.png",
				roomId: "",
				currentUserId: null,
				errorMessage: "",
				isLoading: false,

				// 游戏数据
				game_arena_box: [],
				players: [],
				maxPlayers: 2,

				// 对战状态
				isBattleStarted: false,
				isBattleEnded: false,
				isBattleInitialized: false,
				currentOpeningIndex: -1,
				currentBoxName: '',
				statusAlias: '',

				// 动画数据
				boxSkinsList: [],
				playerResults: [],
				currentResults: [],
				playerSkins: [],
				playerTotals: [],
				playerFinishedStatus: [],
				isAnimating: false,

				// 弹窗状态
				showRewardDetail: false,
				currentBoxDetail: null,
				selectedBoxIndex: -1,

				// 准备阶段
				isPreparingBattle: false,
				prepareCountdown: 3,
				prepareTimer: null,

				// 定时器
				statusPollingTimer: null,
				dataCheckInterval: null,


				// 同步
				battleStartTime: null,
				preparationPhase: false,
				firstBoxProcessed: false,

				// 刷新状态
				isRefreshingBattle: false
			};
		},
		components: {
			navgats
		},
		computed: {
			// 判断当前用户是否已加入房间
			isCurrentUserJoined() {
				if (!this.currentUserId) return false;
				return this.players.some(player => player.user.id === this.currentUserId);
			}
		},
		onLoad(option) {
			this.roomId = option.roomId
			// 获取当前用户ID（实际项目中从登录信息获取）
			this.currentUserId = this.$store?.state.userInfo.id;
			// 进入页面立即调用接口获取玩家信息
			this.onpk(option.roomId)
			// 启动状态轮询
			this.startStatusPolling();
			// 初始化全局WebSocket连接
			this.initGlobalWebSocket();
		},
		onShow() {
			// 如果页面重新显示且状态不是已结束，确保轮询在运行
			if (!this.statusPollingTimer && this.statusAlias !== "已结束") {
				this.onpk(this.roomId);
				this.startStatusPolling();
			}
		},
		onHide() {
			// 页面隐藏时暂停轮询
			this.clearStatusPolling();
			// 移除WebSocket监听器
			this.removeWebSocketListeners();
		},
		onUnload() {
			// 页面卸载时彻底清除所有定时器
			this.cleanupAllTimers();
			// 移除WebSocket监听器
			this.removeWebSocketListeners();
		},
		methods: {
			// 清除所有定时器
			cleanupAllTimers() {
				this.clearStatusPolling();
				if (this.prepareTimer) {
					clearInterval(this.prepareTimer);
					this.prepareTimer = null;
				}
				if (this.dataCheckInterval) {
					clearInterval(this.dataCheckInterval);
					this.dataCheckInterval = null;
				}
			},

			// 启动状态轮询
			startStatusPolling() {
				// 清除可能存在的旧定时器
				this.clearStatusPolling();

				// 如果状态已经是已结束，则不启动轮询
				if (this.statusAlias === "已结束") {
					return;
				}

				// 每3秒检查一次状态
				this.statusPollingTimer = setInterval(() => {
					this.checkStatusUpdate();
				}, 3000);
			},

			// 清除状态轮询
			clearStatusPolling() {
				if (this.statusPollingTimer) {
					clearInterval(this.statusPollingTimer);
					this.statusPollingTimer = null;
				}
			},

			// 检查状态更新
			async checkStatusUpdate() {
				// 如果状态已经是已结束，停止轮询并返回
				if (this.statusAlias === "已结束") {
					this.clearStatusPolling();
					return;
				}

				try {
					const res = await getPKarenaDetail(this.roomId);
					if (res.code === 200) {
						// 更新状态字段
						const newStatusAlias = res.data.status_alias || '';

						// 如果状态变为已结束，先刷新页面数据再启动战斗
						if (newStatusAlias === "已结束") {
							this.statusAlias = newStatusAlias;
							this.clearStatusPolling();

							// 启动页面刷新流程
							this.refreshPageAndStartBattle();
							return;
						}

						// 如果状态没变，不做处理
						if (newStatusAlias === this.statusAlias) {
							return;
						}

						// 更新状态
						this.statusAlias = newStatusAlias;

						// 更新玩家数据
						if (res.data.game_arena_player && res.data.game_arena_player.length) {
							this.players = [...res.data.game_arena_player].sort((a, b) => a.seat - b.seat)
						}

						// 处理箱子数据，添加唯一标识
						if (res.data.game_arena_box && res.data.game_arena_box.length) {
							this.game_arena_box = res.data.game_arena_box.map((box, index) => ({
								...box,
								uniqueId: `${box.box?.id || ''}_${index}` // 生成唯一ID：箱子ID+索引
							}));
						}

						// 如果玩家已填满且战斗未开始，则自动开始战斗
						if (this.players.length >= this.maxPlayers && !this.isBattleStarted && !this
							.battleInitialized) {
							this.battleInitialized = true;
							this.isBattleStarted = true;
							this.startBattleProcess();
						}
					}
				} catch (error) {
					console.error("检查状态更新失败:", error);
				}
			},

			// 刷新页面数据并启动战斗
			async refreshPageAndStartBattle() {
				// 防止重复刷新
				if (this.isRefreshingBattle) return;

				this.isRefreshingBattle = true;
				this.refreshCount = 0;

				try {
					// 多次尝试刷新数据，确保获取到完整的对战结果
					let success = false;
					while (this.refreshCount < this.maxRefreshAttempts && !success) {
						this.refreshCount++;

						// 强制刷新页面数据
						await this.onpk(this.roomId);

						// 检查数据是否完整，特别是第一个箱子的数据
						if (this.game_arena_box.length > 0 &&
							this.players.length > 0 &&
							this.players.every(p => p.game_award && p.game_award.length > 0) &&
							// 特别检查第一个箱子的数据是否存在
							this.game_arena_box[0]?.box?.contains?.length > 0) {
							success = true;
						} else if (this.refreshCount >= this.maxRefreshAttempts) {
							// 如果达到最大尝试次数仍未获取完整数据，也继续启动战斗
							console.warn("已达到最大刷新次数，尝试继续启动战斗");
							success = true;
						} else {
							// 等待1秒后重试
							await new Promise(resolve => setTimeout(resolve, 1000));
						}
					}

					// 启动战斗流程 - 只启动一次
					if (!this.isBattleStarted && !this.battleInitialized) {
						this.battleInitialized = true;
						this.isBattleStarted = true;
						this.startBattleProcess();
					}
				} catch (error) {
					console.error("刷新页面数据失败:", error);
					this.errorMessage = "获取对战结果失败，请稍后重试";
				} finally {
					this.isRefreshingBattle = false;
				}
			},

			// 获取对战详情
			async onpk(id) {
				try {
					this.isLoading = true
					const res = await getPKarenaDetail(id)
					console.log(res);
					if (res.code === 200) {
						// 处理箱子数据，添加唯一标识
						this.game_arena_box = (res.data.game_arena_box || []).map((box, index) => ({
							...box,
							uniqueId: `${box.box?.id || ''}_${index}` // 生成唯一ID：箱子ID+索引
						}));

						// 保存状态字段
						const newStatusAlias = res.data.status_alias || '';

						// 如果状态变为已结束，停止轮询
						if (newStatusAlias === "已结束") {
							this.statusAlias = newStatusAlias;
							this.clearStatusPolling();
						} else {
							this.statusAlias = newStatusAlias;
						}

						// 从接口获取最大玩家数
						this.maxPlayers = res.data.user_num || 2;
						if (this.maxPlayers <= 2) this.maxPlayers = 2;
						if (this.maxPlayers >= 4) this.maxPlayers = 4;

						// 存储玩家数据并按座位号排序
						if (res.data.game_arena_player && res.data.game_arena_player.length) {
							this.players = [...res.data.game_arena_player].sort((a, b) => a.seat - b.seat)
						}

						// 初始化玩家数据结构
						this.initPlayerDataStructures();

						// 检查状态是否为"已结束"，如果是则启动战斗 - 只启动一次
						if (newStatusAlias === "已结束" && !this.isBattleStarted && !this.battleInitialized) {
							this.battleInitialized = true;
							this.isBattleStarted = true;
							this.startBattleProcess();
							return;
						}

						// 如果玩家已填满且战斗未开始，则延迟开始战斗 - 只启动一次
						if (this.players.length >= this.maxPlayers && !this.isBattleStarted && !this
							.battleInitialized) {
							// 延迟3秒后开始对战，给玩家准备时间
							setTimeout(() => {
								console.log('等待了1秒');
								this.battleInitialized = true;
								this.isBattleStarted = true;
								this.startBattleProcess();
							}, 3000);
						} else if (this.isBattleStarted && !this.isBattleEnded) {
							this.continueBattle();
						}
					} else {
						this.errorMessage = res.message || "获取对战信息失败"
					}
				} catch (error) {
					console.error("获取对战详情失败:", error)
					this.errorMessage = "网络错误，获取对战信息失败"
				} finally {
					this.isLoading = false
				}
			},

			// 初始化玩家相关的数据结构
			initPlayerDataStructures() {
				// 初始化玩家结果数组
				this.playerResults = Array(this.maxPlayers).fill([]);

				// 初始化当前结果数组
				this.currentResults = Array(this.maxPlayers).fill(null);

				// 初始化玩家饰品数组
				this.playerSkins = Array(this.maxPlayers).fill().map(() => []);

				// 初始化玩家总价值
				this.playerTotals = Array(this.maxPlayers).fill(0);

				// 初始化动画完成状态
				this.playerFinishedStatus = Array(this.maxPlayers).fill(false);

				// 重置第一个箱子处理标记
				this.firstBoxProcessed = false;
			},

			// 加入房间 - 优化版本
			async joinRoom() {
				playSound("https://img.jingkakeji.com/img/static/music/click.mp3")
				if (this.players.length >= this.maxPlayers) {
					this.errorMessage = "房间已满，无法加入";
					return false;
				}
				try {
					this.isLoading = true;
					// 计算要加入的座位号（从1开始）
					const seat = this.players.length;

					const data = {
						game_arena_id: this.roomId,
						seat: seat
					};
					console.log(data);
					const res = await getPKarenaJoin(data);

					if (res.code === 200) {
						// 加入成功后，强制刷新数据并等待完成
						await this.refreshAndVerifyData();

						// 数据确认无误后，如果玩家已填满则延迟进入准备阶段
						if (this.players.length >= this.maxPlayers && !this.isBattleStarted && !this
							.battleInitialized) {
							// 延迟2秒后开始准备阶段，给玩家缓冲时间
							setTimeout(() => {
								this.startPreparationPhase();
							}, 2000);
						}
						return true;
					} else {
						this.errorMessage = res.message || "加入房间失败";
						return false;
					}
				} catch (error) {
					console.error("加入房间失败:", error);
					this.errorMessage = "网络错误，加入房间失败";
					return false;
				} finally {
					this.isLoading = false;
				}
			},

			// 刷新并验证数据是否完整
			async refreshAndVerifyData() {
				return new Promise((resolve) => {
					let retries = 0;
					const checkData = async () => {
						await this.onpk(this.roomId);
						const isDataReady = this.game_arena_box.length > 0 &&
							this.players.length > 0 &&
							this.players.every(p => p.game_award && p.game_award.length > 0);

						if (isDataReady || retries >= 5) {
							if (this.dataCheckInterval) {
								clearInterval(this.dataCheckInterval);
								this.dataCheckInterval = null;
							}
							resolve(isDataReady);
							return;
						}
						retries++;
					};

					checkData();
					if (!this.dataCheckInterval) {
						this.dataCheckInterval = setInterval(checkData, 1000);
					}
				});
			},

			// 新增：开始战斗准备阶段（添加同步机制）
			startPreparationPhase() {
				console.log('开始战斗准备阶段，时间:', new Date().toISOString());
				this.isPreparingBattle = true;
				this.prepareCountdown = 3; // 3秒准备时间

				// 清除可能存在的旧定时器
				if (this.prepareTimer) {
					clearInterval(this.prepareTimer);
				}

				// 发送准备阶段同步信号给其他玩家
				this.sendPreparationSync();

				// 启动倒计时
				this.prepareTimer = setInterval(() => {
					this.prepareCountdown--;

					if (this.prepareCountdown <= 0) {
						this.isPreparingBattle = false;
						clearInterval(this.prepareTimer);
						this.prepareTimer = null;

						// 准备完成，启动战斗
						this.battleInitialized = true;
						this.isBattleStarted = true;
					}
				}, 1000);
			},

			// 发送准备阶段同步信号
			sendPreparationSync() {
				this.sendWebSocketMessage({
					type: 'battle_prepare',
					roomId: this.roomId,
					countdown: 3,
					timestamp: Date.now()
				});
			},

			// 开始对战流程
			startBattleProcess() {
				console.log('开始对战流程，当前时间:', new Date().toISOString());
				this.isBattleEnded = false;

				// 重置玩家数据
				for (let i = 0; i < this.maxPlayers; i++) {
					this.playerSkins[i] = [];
					this.playerTotals[i] = 0;
				}

				// 重置箱子状态
				this.game_arena_box.forEach(arenaBox => {
					this.$set(arenaBox.box, 'opened', false);
				});

				// 检查数据是否准备好
				if (this.game_arena_box.length === 0) {
					console.warn("箱子数据为空，尝试重新获取...");
					setTimeout(async () => {
						await this.onpk(this.roomId);
						this.openNextBox();
					}, 1000);
					return;
				}

				// 发送对战开始同步信号
				this.sendBattleStartSync();

				// 处理第一个箱子数据
				this.ensureFirstBoxData().then(() => {
					this.openNextBox();
				}).catch(() => {
					console.error("获取第一个箱子数据失败，尝试继续...");
					this.openNextBox();
				});
			},

			// 发送对战开始同步信号
			sendBattleStartSync() {
				this.sendWebSocketMessage({
					type: 'battle_start',
					roomId: this.roomId,
					startTime: Date.now() + 2000,
					timestamp: Date.now()
				});
			},

			// 确保第一个箱子有完整数据
			async ensureFirstBoxData() {
				if (this.game_arena_box.length === 0) {
					throw new Error("没有箱子数据");
				}

				// 检查第一个箱子是否有完整数据
				const firstBox = this.game_arena_box[0].box;
				if (firstBox && firstBox.contains && firstBox.contains.length > 0) {
					return true;
				}

				// 第一个箱子数据不完整，尝试重新获取
				let attempts = 0;
				const maxAttempts = 3;

				while (attempts < maxAttempts) {
					attempts++;
					console.log(`尝试获取第一个箱子数据，第${attempts}次`);
					await this.onpk(this.roomId);

					const newFirstBox = this.game_arena_box[0]?.box;
					if (newFirstBox && newFirstBox.contains && newFirstBox.contains.length > 0) {
						return true;
					}

					// 等待500ms再试
					await new Promise(resolve => setTimeout(resolve, 500));
				}

				throw new Error(`经过${maxAttempts}次尝试，仍无法获取第一个箱子的完整数据`);
			},

			// 继续对战（用于从接口重新获取数据后继续）
			continueBattle() {
				// 如果正在动画中，不进行操作
				if (this.isAnimating) return;

				// 检查是否有未开的箱子
				const unopenedBoxIndex = this.game_arena_box.findIndex(
					arenaBox => arenaBox.box && !arenaBox.box.opened
				);

				if (unopenedBoxIndex !== -1) {
					this.currentOpeningIndex = unopenedBoxIndex - 1;
					this.openNextBox();
				} else {
					this.endBattle();
				}
			},

			// 打开下一个箱子 - 优化版本（添加动画同步机制）
			openNextBox() {

				const nextIndex = this.currentOpeningIndex + 1;

				// 检查是否所有箱子都已开完
				if (nextIndex >= this.game_arena_box.length) {
					this.endBattle();
					return;
				}

				console.log('开始开箱，箱子索引:', nextIndex, '时间:', new Date().toISOString());
				playSound("https://img.jingkakeji.com/img/static/music/open2.mp3")
				// 重置动画状态
				this.playerFinishedStatus = Array(this.maxPlayers).fill(false);
				this.isAnimating = true;

				// 设置当前开箱索引和名称
				this.currentOpeningIndex = nextIndex;
				const currentArenaBox = this.game_arena_box[nextIndex];
				const currentBox = currentArenaBox.box;
				this.currentBoxName = currentBox ? currentBox.name : '';

				// 检查当前箱子数据是否完整，不完整则延迟重试
				if (!currentBox || !currentBox.contains) {
					console.error('当前箱子数据不完整，延迟重试', currentBox);
					this.isAnimating = false;
					setTimeout(() => {
						this.openNextBox();
					}, 1000);
					return;
				}

				// 标记箱子为已开启状态
				this.$set(currentBox, 'opened', true);

				// 准备当前箱子的饰品数据
				this.boxSkinsList = currentBox.contains.map(item => item.skins || {});

				// 获取当前箱子的开箱结果 - 增加重试机制
				this.currentResults = [];
				this.playerResults = [];
				let hasInvalidData = false;

				for (let i = 0; i < this.maxPlayers; i++) {
					this.currentResults[i] = this.getPlayerAwardByBoxIndexAndId(i, nextIndex, currentBox.id);
					this.playerResults[i] = this.currentResults[i] ? [this.currentResults[i].award_id] : [];

					// 检查是否有无效数据
					if (!this.currentResults[i]) {
						hasInvalidData = true;
					}
				}

				// 对于第一个箱子，增加额外的数据验证和处理
				if (nextIndex === 0 && !this.firstBoxProcessed) {
					this.firstBoxProcessed = true;
					if (hasInvalidData) {
						console.warn('第一个箱子检测到无效的饰品数据，尝试额外处理...');
						// 对于第一个箱子，尝试更宽松的匹配方式
						for (let i = 0; i < this.maxPlayers; i++) {
							if (!this.currentResults[i] && this.players[i] && this.players[i].game_award && this.players[i]
								.game_award.length > 0) {
								// 直接取第一个奖励作为备选
								this.currentResults[i] = this.players[i].game_award[0];
								this.playerResults[i] = this.currentResults[i] ? [this.currentResults[i].award_id] : [];
								hasInvalidData = false;
							}
						}
					}
				}

				// 如果有无效数据，延迟一段时间后重试
				if (hasInvalidData) {
					console.warn('检测到无效的饰品数据，延迟重试...');
					this.isAnimating = false;

					// 再次尝试获取完整数据
					setTimeout(async () => {
						await this.onpk(this.roomId);
						this.openNextBox();
					}, 1000);
					return;
				}

				// 发送动画同步信号给其他玩家
				this.sendAnimationSync(nextIndex);

				// 延迟启动动画，确保所有数据都已准备好
				setTimeout(() => {
					this.startSynchronizedAnimation();
				}, 500);
			},

			// 发送动画同步信号
			sendAnimationSync(boxIndex) {
				this.sendWebSocketMessage({
					type: 'animation_sync',
					roomId: this.roomId,
					action: 'start_animation',
					boxIndex: boxIndex,
					timestamp: Date.now()
				});
			},

			// 同步启动动画
			startSynchronizedAnimation() {
				console.log('同步启动动画，时间:', new Date().toISOString());
				for (let i = 0; i < this.maxPlayers; i++) {
					if (this.players[i] && this.$refs[`player${i + 1}Box`] && this.$refs[`player${i + 1}Box`][0]) {
						if (!this.playerFinishedStatus[i]) {
							this.$refs[`player${i + 1}Box`][0].start();
						}
					}
				}
			},

			// 通过箱子索引和ID精确匹配奖励
			getPlayerAwardByBoxIndexAndId(playerIndex, boxIndex, boxId) {
				if (!this.players[playerIndex] || !this.players[playerIndex].game_award) {
					return null;
				}

				// 查找玩家针对指定索引和ID的箱子的奖励
				// 优先匹配同时包含box_id和box_index的奖励
				let award = this.players[playerIndex].game_award.find(award =>
					award.box_id === boxId && award.box_index === boxIndex
				);

				// 如果没有找到带索引的匹配，使用兼容方案（假设奖励顺序与箱子顺序一致）
				if (!award && this.players[playerIndex].game_award.length > boxIndex) {
					award = this.players[playerIndex].game_award[boxIndex];
					// 二次验证ID是否匹配
					if (award && award.box_id === boxId) {
						return award;
					}
				}

				// 对于第一个箱子，增加额外的容错机制
				if (boxIndex === 0 && !award) {
					console.warn(`玩家${playerIndex}的第一个箱子奖励未找到，尝试更宽松的匹配`);
					// 尝试只匹配box_id，不严格匹配index
					award = this.players[playerIndex].game_award.find(award => award.box_id === boxId);

					if (!award) {
						// 如果还是没找到，尝试取第一个奖励
						award = this.players[playerIndex].game_award[0] || null;
					}
				}

				return award || null;
			},

			// 获取指定玩家的结果
			getPlayerResult(playerIndex) {
				return this.playerResults[playerIndex] || [];
			},

			// 玩家开箱完成
			onPlayerFinish(playerIndex) {
				this.playerFinishedStatus[playerIndex] = true;
				if (this.currentResults[playerIndex]) {
					this.addSkinToPlayer(playerIndex, this.currentResults[playerIndex]);
				}
				this.checkAllPlayersFinished();
			},

			// 检查所有玩家是否都完成了开箱
			checkAllPlayersFinished() {
				// 检查所有已加入的玩家是否都完成了动画
				const allFinished = this.players.every((player, index) =>
					this.playerFinishedStatus[index]
				);
				if (allFinished) {
					// 隐藏动画
					this.isAnimating = false;

					// 短暂停留后开下一个箱子
					setTimeout(() => {
						this.currentResults = Array(this.maxPlayers).fill(null);
						this.openNextBox();
					}, 2000);
				}
			},

			// 添加饰品给玩家
			addSkinToPlayer(playerIndex, skinData) {
				if (!skinData || !skinData.skins) return;

				// 找到对应的箱子信息（使用唯一ID匹配）
				const boxInfo = this.game_arena_box.find(arenaBox =>
					arenaBox.box && arenaBox.box.id === skinData.box_id
				);

				// 保存完整的饰品信息，包括来源箱子
				this.playerSkins[playerIndex].push({
					...skinData,
					box: boxInfo ? boxInfo.box : {
						name: '未知箱子'
					},
					boxIndex: skinData.box_index // 记录箱子索引
				});
				console.log(this.playerSkins, '’123');

				// 更新玩家总价值
				this.playerTotals[playerIndex] = (
					parseFloat(this.playerTotals[playerIndex]) +
					parseFloat(skinData.skins.bean || 0)
				).toFixed(2);
			},

			// 获取指定玩家的结果
			getPlayerResult(playerIndex) {
				return this.playerResults[playerIndex] || [];
			},

			// 获取指定玩家的饰品列表
			getPlayerSkins(playerIndex) {
				console.log('已开', this.playerSkins);
				return this.playerSkins[playerIndex] || [];
			},

			// 获取指定玩家的总价值
			getPlayerTotal(playerIndex) {
				return this.playerTotals[playerIndex] || 0;
			},

			// 获取除指定玩家外其他玩家的最高总价值
			getMaxOtherPlayerTotal(excludeIndex) {
				let maxTotal = 0;
				for (let i = 0; i < this.maxPlayers; i++) {
					if (i !== excludeIndex && this.players[i]) {
						const total = parseFloat(this.getPlayerTotal(i));
						if (total > maxTotal) {
							maxTotal = total;
						}
					}
				}
				return maxTotal;
			},

			// 判断是否为平局
			isDraw() {
				if (!this.isBattleEnded || this.players.length < 2) {
					return false;
				}

				// 获取所有玩家的总价值
				const playerTotals = [];
				for (let i = 0; i < this.maxPlayers; i++) {
					if (this.players[i]) {
						playerTotals.push(parseFloat(this.getPlayerTotal(i)));
					}
				}

				// 如果所有玩家的价值都相等，则为平局
				if (playerTotals.length >= 2) {
					const firstTotal = playerTotals[0];
					return playerTotals.every(total => Math.abs(total - firstTotal) < 0.01); // 使用0.01的容差来处理浮点数精度问题
				}

				return false;
			},

			// 判断指定玩家是否胜利
			isPlayerWinner(playerIndex) {
				if (!this.isBattleEnded || this.isDraw() || !this.players[playerIndex]) {
					return false;
				}

				const playerTotal = parseFloat(this.getPlayerTotal(playerIndex));
				const maxOtherTotal = this.getMaxOtherPlayerTotal(playerIndex);

				return playerTotal > maxOtherTotal;
			},

			// 结束对战
			endBattle() {
				this.isBattleEnded = true;
				this.isAnimating = false;

				// 如果不是平局，将失败者的饰品转移给胜利者
				if (!this.isDraw()) {
					this.transferSkinsToWinner();
				}

				// 战斗结束后清除轮询
				this.clearStatusPolling();
			},

			// 将失败者的饰品转移给胜利者
			transferSkinsToWinner() {
				// 找到胜利者
				let winnerIndex = -1;
				for (let i = 0; i < this.maxPlayers; i++) {
					if (this.players[i] && this.isPlayerWinner(i)) {
						winnerIndex = i;
						break;
					}
				}

				// 如果找到胜利者，将其他玩家的饰品转移给他
				if (winnerIndex !== -1) {
					for (let i = 0; i < this.maxPlayers; i++) {
						if (i !== winnerIndex && this.players[i] && this.playerSkins[i].length > 0) {
							// 将失败者的饰品添加到胜利者的饰品列表中
							this.playerSkins[winnerIndex] = this.playerSkins[winnerIndex].concat(this.playerSkins[i]);

							// 将失败者的总价值加到胜利者身上
							const loserTotal = parseFloat(this.getPlayerTotal(i));
							this.playerTotals[winnerIndex] = (
								parseFloat(this.playerTotals[winnerIndex]) + loserTotal
							).toFixed(2);

							// 清空失败者的饰品和总价值
							this.playerSkins[i] = [];
							this.playerTotals[i] = 0;
						}
					}

					console.log('饰品转移完成，胜利者获得所有饰品');
				}
			},

			// 显示箱子奖励详情
			showBoxRewards(boxDetail, index) {
				this.currentBoxDetail = boxDetail;
				this.selectedBoxIndex = index;
				this.showRewardDetail = true;
			},

			// 关闭奖励详情弹窗
			closeRewardDetail() {
				this.showRewardDetail = false;
				this.currentBoxDetail = null;
				this.selectedBoxIndex = -1;
			},

			// ========== 全局WebSocket 相关方法 ==========

			// 初始化全局WebSocket
			initGlobalWebSocket() {
				// 初始化全局WebSocket连接
				globalWebSocket.init();

				// 添加消息监听器
				globalWebSocket.on('message', this.handleGlobalWebSocketMessage);
				globalWebSocket.on('open', this.onGlobalWebSocketOpen);
			},

			// 移除WebSocket监听器
			removeWebSocketListeners() {
				globalWebSocket.off('message', this.handleGlobalWebSocketMessage);
				globalWebSocket.off('open', this.onGlobalWebSocketOpen);
			},

			// 全局WebSocket事件处理
			onGlobalWebSocketOpen(e) {
				console.log('全局WebSocket连接成功', e);
				this.subscribeToRoom();
			},

			handleGlobalWebSocketMessage(e) {
				// 处理全局WebSocket消息
				this.handleWebSocketMessage(e.data);
			},

			// 订阅房间消息
			subscribeToRoom() {
				const message = {
					type: 'subscribe',
					roomId: this.roomId,
					userId: this.currentUserId
				};
				this.sendWebSocketMessage(message);
			},

			// 处理WebSocket消息
			handleWebSocketMessage(data) {
				try {
					// 处理心跳消息
					if (data === 'ping' || data === 'pong') {
						console.log('收到心跳消息:', data);
						return;
					}

					// 尝试解析JSON消息
					let message;
					try {
						message = JSON.parse(data);
					} catch (parseError) {
						// console.warn('消息不是有效的JSON格式:', data);
						return;
					}

					console.log('解析WebSocket消息:', message);

					// 验证消息格式
					if (!message || typeof message !== 'object') {
						console.warn('消息格式无效:', message);
						return;
					}

					switch (message.type) {
						case 'battle_start':
							// 收到对战开始信号，同步开始对战
							this.handleBattleStartSync(message);
							break;
						case 'battle_prepare':
							// 收到准备阶段信号
							this.handleBattlePrepareSync(message);
							break;
						case 'animation_sync':
							// 收到动画同步信号
							this.handleAnimationSync(message);
							break;
						case 'player_join':
							// 玩家加入房间
							this.handlePlayerJoin(message);
							break;
						case 'player_leave':
							// 玩家离开房间
							this.handlePlayerLeave(message);
							break;
						default:
							console.log('未知消息类型:', message.type);
					}
				} catch (error) {
					console.error('处理WebSocket消息失败:', error);
				}
			},

			// 处理对战开始同步
			handleBattleStartSync(message) {
				console.log('收到对战开始同步信号:', message);

				// 如果当前玩家已经在房间中，同步开始对战
				if (this.isCurrentUserJoined && !this.isBattleStarted) {
					// 设置同步开始时间
					this.battleStartTime = message.startTime;

					// 延迟启动对战，确保所有玩家同步
					const delay = Math.max(0, message.startTime - Date.now());
					setTimeout(() => {
						this.battleInitialized = true;
						this.isBattleStarted = true;
						this.startBattleProcess();
					}, delay);
				}
			},

			// 处理对战准备同步
			handleBattlePrepareSync(message) {
				console.log('收到对战准备同步信号:', message);

				if (this.isCurrentUserJoined && !this.isBattleStarted) {
					this.preparationPhase = true;
					this.prepareCountdown = message.countdown || 3;

					// 显示准备倒计时
					this.isPreparingBattle = true;

					// 启动倒计时
					this.prepareTimer = setInterval(() => {
						this.prepareCountdown--;

						if (this.prepareCountdown <= 0) {
							this.isPreparingBattle = false;
							this.preparationPhase = false;
							clearInterval(this.prepareTimer);
							this.prepareTimer = null;
						}
					}, 1000);
				}
			},

			// 处理动画同步
			handleAnimationSync(message) {
				console.log('收到动画同步信号:', message);

				// 同步开始动画
				if (message.action === 'start_animation') {
					this.syncStartAnimation(message.boxIndex);
				}
			},

			// 处理玩家加入
			handlePlayerJoin(message) {
				console.log('玩家加入房间:', message);
				// 刷新房间数据
				this.onpk(this.roomId);
			},

			// 处理玩家离开
			handlePlayerLeave(message) {
				console.log('玩家离开房间:', message);
				// 刷新房间数据
				this.onpk(this.roomId);
			},

			// 发送WebSocket消息
			sendWebSocketMessage(message) {
				try {
					// 处理心跳消息
					if (message === 'ping' || message === 'pong') {
						globalWebSocket.send(message);
						return;
					}

					// 处理JSON消息
					const data = JSON.stringify(message);
					globalWebSocket.send(data);
				} catch (e) {
					console.error('发送WebSocket消息失败:', e);
				}
			},

			// 同步开始动画
			syncStartAnimation(boxIndex) {
				console.log('同步开始动画，箱子索引:', boxIndex);

				// 设置当前开箱索引
				this.currentOpeningIndex = boxIndex - 1;

				// 延迟启动动画，确保所有玩家同步
				setTimeout(() => {
					this.openNextBox();
				}, 500);
			},

		}
	};
</script>

<style lang="scss" scoped>
	.csgo-case-battle {
		background-color: #1a1a1a;
		color: #fff;
		height: 100vh;
		position: relative;
		background: url("https://img.jingkakeji.com/img/static/new_pks_pk/bg.png");
		background-repeat: no-repeat;
		background-position: center;
		background-size: cover;
		background-attachment: fixed;
		display: flex;
		flex-direction: column;
		align-items: center;
		overflow: hidden;

		/* 宝箱区域样式 */
		.cases-container {
			width: 100%;
			margin-bottom: 10rpx;

			.cases-scroll {
				width: 100%;
				white-space: nowrap;
				background-color: rgba(255, 255, 255, 0.3);

				.cases-list {
					display: inline-flex;
					padding: 10rpx 0;


					.case-item {
						width: 165rpx;
						height: 165rpx;
						display: inline-flex;
						margin-left: 20rpx;
						flex-direction: column;
						align-items: center;
						transition: all 0.3s ease;
						cursor: pointer;
						background-image: url("https://img.jingkakeji.com/img/static/new_pks_pk/item_bg.png");
						background-size: contain;
						background-position: center;
						background-repeat: no-repeat;

						&.active {
							box-shadow: 0 0 5rpx 5rpx white;
							border-radius: 20rpx;
						}

						&.opened {
							opacity: 0.7;
						}

						&.selected {
							box-shadow: 0 0 15rpx 5rpx #4cd964;
							border-radius: 10rpx;
						}

						.case-cover {
							width: 100rpx;
							height: 55rpx;
							border-radius: 10rpx;
						}

						.case-name {
							font-size: 24rpx;
							margin-top: 10rpx;
							text-align: center;
							white-space: normal;
							color: #31296A;
						}

						.case-price {
							width: 100%;
							height: 45rpx;
							font-size: 22rpx;
							text-align: center;
							line-height: 45rpx;
							color: #FBDC3B;
							margin-top: 10rpx;
							display: flex;
							align-items: center;
							justify-content: center;

							.icon {
								width: 20rpx;
								height: 20rpx;
								background-image: url("https://img.jingkakeji.com/img/static/new_pk/money.png");
								background-size: contain;
								background-position: center;
								background-repeat: no-repeat;
								margin-right: 10rpx;
							}
						}
					}
				}
			}
		}

		/* 房间信息 */
		.room-info {
			width: 95%;
			height: 80rpx;
			text-align: center;
			margin: 20rpx 0;
			background: url("https://img.jingkakeji.com/img/static/new_pks_pk/room_status_bg.png");
			background-repeat: no-repeat;
			background-position: center;
			background-size: contain;
			border-radius: 8rpx;
			line-height: 80rpx;

			.room-status {
				font-size: 26rpx;

				.status-text {
					color: #4cd964;
					font-weight: bold;
					margin-left: 10rpx;
				}
			}
		}

		/* 玩家预览区域 - 战斗未开始时 */
		.players-preview {
			width: 95%;
			margin: 30rpx 0;

			.players-grid {
				width: 100%;
				height: 220rpx;
				border-radius: 10rpx;
				display: flex;
				justify-content: space-evenly;

				.player-slot {
					width: 220rpx;
					height: 220rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					border-radius: 8rpx;
					transition: all 0.3s ease;
					background-image: url("https://img.jingkakeji.com/img/static/new_pks_pk/user_bg.png");
					background-size: contain;
					background-position: center;
					background-repeat: no-repeat;

					.avatar,
					.avatar-placeholder {
						width: 80rpx;
						height: 80rpx;
					}

					.avatar {
						border: 2rpx solid white;
					}

					.avatar-placeholder {
						display: flex;
						justify-content: center;
						align-items: center;
						background-color: #7869da;
						border: 1px solid white;

						.add-icon {
							font-size: 40rpx;
							color: white;
						}
					}

					.player-name {
						margin-top: 15rpx;
						font-size: 26rpx;
						text-align: center;
						max-width: 100%;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					.status {
						margin-top: 8rpx;
						font-size: 22rpx;
						padding: 3rpx 15rpx;
						border-radius: 12rpx;

						&.joined {
							color: #4cd964;
							background-color: rgba(0, 0, 0, 0.3);
						}

						&.waiting {
							color: red;
							background-color: rgba(0, 0, 0, 0.3);
						}
					}
				}
			}
		}

		/* 加入房间按钮 */
		.join-room {
			display: flex;
			justify-content: center;
			margin: 30rpx 0;

			.join-btn {
				width: 350rpx;
				height: 80rpx;
				line-height: 80rpx;
				background: url("https://img.jingkakeji.com/img/static/aacomegame.png");
				background-repeat: no-repeat;
				background-position: center;
				background-size: cover;
				color: #fff;
				font-size: 28rpx;
				border: none;
			}
		}

		/* 等待其他玩家提示 */
		.waiting-players {
			text-align: center;
			margin: 30rpx 0;

			.waiting-text {
				font-size: 26rpx;
				color: #ffcc00;
				padding: 15rpx;
				background-color: rgba(255, 204, 0, 0.1);
				border-radius: 8rpx;
				display: inline-block;
			}
		}

		/* 房间满人等待开始提示 */
		.room-full-waiting {
			text-align: center;
			margin: 30rpx 0;
			animation: fadeIn 0.5s ease-in;

			.waiting-content {
				background: linear-gradient(135deg, #4cd964 0%, #2ecc71 100%);
				padding: 30rpx 40rpx;
				border-radius: 15rpx;
				box-shadow: 0 5rpx 15rpx rgba(76, 217, 100, 0.3);
				display: inline-block;

				.waiting-icon {
					font-size: 60rpx;
					margin-bottom: 15rpx;
					animation: bounce 1s infinite;
				}

				.waiting-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #fff;
					margin-bottom: 10rpx;
				}

				.waiting-subtitle {
					font-size: 26rpx;
					color: #fff;
					opacity: 0.9;
				}
			}
		}

		@keyframes fadeIn {
			from {
				opacity: 0;
				transform: translateY(20rpx);
			}

			to {
				opacity: 1;
				transform: translateY(0);
			}
		}

		@keyframes bounce {

			0%,
			20%,
			50%,
			80%,
			100% {
				transform: translateY(0);
			}

			40% {
				transform: translateY(-10rpx);
			}

			60% {
				transform: translateY(-5rpx);
			}
		}

		/* 准备阶段倒计时 */
		.preparation-phase {
			position: fixed;
			top: 0;
			left: 0;
			width: 100vw;
			height: 100vh;
			background: rgba(0, 0, 0, 0.8);
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 9999;

			.preparation-content {
				text-align: center;
				background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
				padding: 60rpx 40rpx;
				border-radius: 20rpx;
				box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);

				.preparation-title {
					font-size: 36rpx;
					font-weight: bold;
					color: #fff;
					margin-bottom: 30rpx;
				}

				.countdown-display {
					font-size: 120rpx;
					font-weight: bold;
					color: #ff6b6b;
					text-shadow: 0 0 20rpx rgba(255, 107, 107, 0.5);
					margin: 20rpx 0;
					animation: pulse 1s infinite;
				}

				.preparation-subtitle {
					font-size: 28rpx;
					color: #fff;
					opacity: 0.8;
				}
			}
		}

		@keyframes pulse {
			0% {
				transform: scale(1);
			}

			50% {
				transform: scale(1.1);
			}

			100% {
				transform: scale(1);
			}
		}

		/* 对战区域样式 */
		.battle-area {
			width: 95vw;
			height: 620rpx;
			background-color: rgba(255, 255, 255, 0.2);
			border-radius: 20rpx;

			.players-battle-info {
				margin-bottom: 30rpx;
				border-radius: 10rpx;
				display: flex;
				align-items: center;
				margin-top: 20rpx;
				justify-content: space-evenly;

				.battle-player {
					width: 220rpx;
					height: 220rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: space-evenly;
					border-radius: 8rpx;
					background-image: url("https://img.jingkakeji.com/img/static/new_pks_pk/user_bg.png");
					background-size: contain;
					background-position: center;
					background-repeat: no-repeat;

					&.winner {
						background-color: rgba(255, 215, 0, 0.2);
						border: 2rpx solid #ffd700;
					}

					.avatar {
						width: 70rpx;
						height: 70rpx;
						border: 2rpx solid white;
					}

					.player-name {
						margin-top: 10rpx;
						font-size: 26rpx;
						text-align: center;
					}

					.total-value {
						margin-top: 5rpx;
						font-size: 24rpx;
						color: #FBDC3B;
						display: flex;
						align-items: center;

						.icon {
							width: 20rpx;
							height: 20rpx;
							background-image: url("https://img.jingkakeji.com/img/static/new_pk/money.png");
							background-size: contain;
							background-position: center;
							background-repeat: no-repeat;
							margin-right: 10rpx;
							margin-top: 5rpx;
						}
					}
				}
			}

			.battle-status {
				text-align: center;
				padding: 15rpx;
				margin-bottom: 20rpx;
				background-image: url("https://img.jingkakeji.com/img/static/new_pks_pk/title_bg.png");
				background-size: 100% 100%;
				font-size: 26rpx;
				color: white;

				&.ended {
					color: white;
					font-weight: bold;
				}

				.current-box {
					margin-left: 15rpx;
					color: #ffcc00;
				}
			}

			/* 动画容器样式 - 确保动画在玩家信息下方 */
			.animation-container {
				width: 100%;
				height: 200rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				width: 100%;
				margin-top: 20rpx;
				overflow: hidden;
				background-image: url("https://img.jingkakeji.com/img/static/new_pks_pk/pk_ing_bg.png");
				background-size: 100% 100%;
				position: relative;
			}

			.victory {
				width: 100%;
				height: 200rpx;
				display: flex;
				justify-content: space-evenly;

				.item {
					width: 220rpx;
					height: 220rpx;

					.item_box {
						width: 220rpx;
						height: 220rpx;
						background-image: url("https://img.jingkakeji.com/img/static/new_pks_pk/win.webp");
						background-size: 100% 100%;
					}
				}
			}

			.line {
				width: 99%;
				border: 1px solid white;
				position: absolute;
				top: 50%;
				left: 0;
				z-index: 999999;
			}

			/* 开箱动画区域样式 */
			.opening-area {
				display: flex;
				justify-content: center;
				width: 100%;
				padding: 20rpx;
				box-sizing: border-box;

				.player-opening {
					flex: 1;
					display: flex;
					justify-content: center;
					padding: 0 10rpx;
				}
			}

			/* 当前开出饰品显示样式 */
			.current-skin-display {
				width: 100%;
				height: 100%;
				display: flex;
				justify-content: space-evenly;
				align-items: center;
				box-sizing: border-box;
				z-index: 999999999;

				.current-skin {
					height: 100%;
					display: flex;
					flex-direction: column;
					align-items: center;

					.skin-image {
						width: 150rpx;
						height: 150rpx;
						background-size: cover;
						background-position: center;
						background-repeat: no-repeat;
						border-radius: 8rpx;
					}

					.skin-value {
						margin-top: 10rpx;
						font-size: 24rpx;
						color: #FBDC3B;
					}
				}
			}
		}

		/* 已开饰品列表样式 */
		.opened-skins {
			width: 95vw;
			height: 620rpx;
			background-color: rgba(255, 255, 255, 0.2);
			border-radius: 0 0 20rpx 20rpx;

			.players-skins-container {
				width: 100%;
				height: 100%;
				display: flex;
				justify-content: space-evenly;


				.player-skins {
					width: 220rpx;
					height: 600rpx;
					border-radius: 10rpx;
					border: 1px solid white;
					overflow: hidden;

					.title {
						width: 100%;
						height: 50rpx;
						white-space: nowrap;
						line-height: 50rpx;
						text-indent: 10rpx;
						overflow: hidden;
						text-overflow: ellipsis;
						font-size: 26rpx;
						margin-bottom: 15rpx;
						color: white;
						padding-bottom: 10rpx;
						background-color: #7869DA;
					}

					.skins-list {
						width: 90%;
						height: calc(100% - 80rpx);
						overflow-y: auto;
						margin: 0 auto;

						.skin-item {
							width: 90%;
							height: 180rpx;
							text-align: center;
							margin: 0 auto;
							// justify-content: space-evenly;
							background-size: contain;
							background-position: center;
							background-repeat: no-repeat;
							position: relative;
							display: flex;
							flex-direction: column;
							justify-content: space-evenly;

							image {
								width: 70rpx;
								height: 80rpx;
							}

							.skin-dura {
								width: 95rpx;
								height: 35rpx;
								background-color: #7869DA;
								font-size: 20rpx;
								color: white;
								border-radius: 0 0 10rpx 0;
								position: absolute;
								text-align: center;
								line-height: 35rpx;
								top: 0;
								left: 0;
							}

							.skin-details {
								width: 200rpx;
								height: 80rpx;
								display: flex;
								flex-direction: column;
								align-items: center;
								justify-content: space-between;


								.skin-name {
									width: 90%;
									text-indent: 10rpx;
									font-size: 24rpx;
									white-space: nowrap;
									overflow: hidden;
									text-overflow: ellipsis;
								}



								.skin-price {
									font-size: 22rpx;
									color: #FBDC3B;
									display: flex;
									align-items: center;

									.icon {
										width: 20rpx;
										height: 20rpx;
										background-image: url("https://img.jingkakeji.com/img/static/new_pk/money.png");
										background-size: contain;
										background-position: center;
										background-repeat: no-repeat;
										margin-right: 10rpx;
									}
								}

								.skin-box {
									font-size: 20rpx;
									color: #666;
								}
							}
						}
					}
				}
			}
		}

		/* 奖励详情弹窗样式 */
		.reward-detail-modal {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 999;

			.modal-overlay {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background-color: rgba(0, 0, 0, 0.7);
			}

			.modal-content {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				width: 90%;
				max-height: 80vh;
				background-color: #1a1a1a;
				border-radius: 15rpx;
				overflow: hidden;

				.modal-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 20rpx;
					background-color: #333;

					.modal-title {
						font-size: 28rpx;
						font-weight: bold;
					}

					.close-btn {
						width: 60rpx;
						height: 60rpx;
						line-height: 60rpx;
						text-align: center;
						background-color: transparent;
						color: #fff;
						font-size: 36rpx;
						padding: 0;
						border: none;
					}
				}

				.reward-list {
					padding: 20rpx;
					max-height: calc(80vh - 100rpx);
					overflow-y: auto;
					background-color: #D8D3FB;

					.reward-item {
						display: flex;
						padding: 15rpx 0;
						border-bottom: 1px solid rgba(255, 255, 255, 0.1);

						image {
							width: 100rpx;
							height: 100rpx;
							border-radius: 5rpx;
						}

						.reward-info {
							margin-left: 20rpx;
							flex: 1;

							.reward-name {
								font-size: 26rpx;
							}

							.reward-dura {
								font-size: 22rpx;
								color: #999;
								margin-top: 5rpx;
							}

							.reward-value {
								font-size: 24rpx;
								color: #00ff00;
								margin-top: 5rpx;
							}
						}
					}
				}
			}
		}

		/* 错误提示样式 */
		.error-toast {
			position: fixed;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			z-index: 1000;

			.toast-content {
				background-color: rgba(0, 0, 0, 0.8);
				padding: 30rpx;
				border-radius: 10rpx;
				font-size: 28rpx;
				text-align: center;

				.close-btn {
					margin-top: 20rpx;
					background-color: #ff3300;
					color: #fff;
					border: none;
					padding: 10rpx 30rpx;
					border-radius: 5rpx;
					font-size: 26rpx;
				}
			}
		}

		/* 加载中样式 */
		.loading,
		.preparing-battle,
		.refreshing-battle {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.5);
			display: flex;
			justify-content: center;
			align-items: center;
			z-index: 999;

			.loading-content,
			.preparing-content,
			.refreshing-content {
				display: flex;
				flex-direction: column;
				align-items: center;

				.spinner {
					width: 60rpx;
					height: 60rpx;
					border: 5rpx solid rgba(255, 255, 255, 0.3);
					border-radius: 50%;
					border-top-color: #fff;
					animation: spin 1s ease-in-out infinite;
				}

				.loading-text,
				.preparing-text,
				.refreshing-text {
					margin-top: 20rpx;
					font-size: 28rpx;
					color: #fff;
				}
			}
		}

		@keyframes spin {
			to {
				transform: rotate(360deg);
			}
		}

		/* 皮肤项样式 */
		.skin-item {
			width: 100%;
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
</style>